package com.qire.manhua.model.viewModel.impl;

import android.app.Activity;
import android.graphics.Rect;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.view.View;
import android.widget.BaseAdapter;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.BuyMembershipController;
import com.qire.manhua.dal.service.BuyMembershipService;
import com.qire.manhua.databinding.LayoutBuyMembershipFreeComicItemBinding;
import com.qire.manhua.databinding.LayoutBuyMembershipPackageItemBinding;
import com.qire.manhua.databinding.LayoutBuyMembershipVipPrivilegeItemBinding;
import com.qire.manhua.dialog.BuyResultTipsDialog;
import com.qire.manhua.dialog.BuyResultTipsDialog.PayTipType;
import com.qire.manhua.dialog.SpecialEventDialog;
import com.qire.manhua.dialog.TipsConfirmDialog;
import com.qire.manhua.model.enumeration.PaymentMethod;
import com.qire.manhua.model.enumeration.VipPrivilegeType;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;
import androidx.recyclerview.widget.RecyclerView.ItemDecoration;

public class BuyMembershipViewModel extends BaseViewModel implements IViewModel {

    private BuyMembershipService buyMembershipService = new BuyMembershipService(this);

    private final ArrayList<MembersPackageItemViewModel> membersPackageList = new ArrayList<>();
    private final ArrayList<MembersFreeComicItemViewModel> freeComicList = new ArrayList<>();
    private final ArrayList<VipPrivilegeItemViewModel> vipPrivilegeList = new ArrayList<>();

    private final SummerBindAdapter membersPackageAdapter = new SummerBindAdapter(membersPackageList);
    private final SummerRecyclerBindAdapter freeComicAdapter = new SummerRecyclerBindAdapter(freeComicList);
    private final SummerBindAdapter vipPrivilegeAdapter = new SummerBindAdapter(vipPrivilegeList);

    private final ItemDecoration[] freeComicItemDecorations = {new GridSpacingItemDecoration(3, EquipmentInfoUtil.dip2px(10), false)};

    private Activity activity;

    private MembersPackageItemViewModel selectPackageItem;

    private boolean isReceive = false;

    public BuyMembershipViewModel() {
        vipPrivilegeList.add(new VipPrivilegeItemViewModel(VipPrivilegeType.Discount));
        vipPrivilegeList.add(new VipPrivilegeItemViewModel(VipPrivilegeType.FreeRead));
        vipPrivilegeList.add(new VipPrivilegeItemViewModel(VipPrivilegeType.LimitTimeRead));

        vipPrivilegeList.add(new VipPrivilegeItemViewModel(VipPrivilegeType.BeanReward));
        vipPrivilegeList.add(new VipPrivilegeItemViewModel(VipPrivilegeType.ExclusiveIcon));
        vipPrivilegeList.add(new VipPrivilegeItemViewModel(VipPrivilegeType.PersonalityBulletScreen));
    }

    @Override
    public int getVariableId() {
        return BR.buyMembershipViewModel;
    }

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(Activity activity, BuyMembershipController controller) {
        this.activity = activity;
        membersPackageAdapter.setEventProcess(controller);
        freeComicAdapter.setEventProcess(controller);
        vipPrivilegeAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        activity = null;
        buyMembershipService = null;
        membersPackageAdapter.setEventProcess(null);
        freeComicAdapter.setEventProcess(null);
        vipPrivilegeAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region # 数据
    private void toggleSelectItem(MembersPackageItemViewModel itemViewModel) {
        if(ObjectUtil.nonNull(selectPackageItem)) {
            selectPackageItem.setHaveChosen(false);
        }

        if(ObjectUtil.notEquals(selectPackageItem, itemViewModel)) {
            selectPackageItem = itemViewModel;
            itemViewModel.setHaveChosen(true);
        } else {
            selectPackageItem = null;
        }
        refreshBuyButtonUI();
    }

    public void buyBuyMembership(PaymentMethod paymentMethod) {
        buyMembershipService.buyBuyMembership(selectPackageItem, paymentMethod, activity.getClass().getSimpleName());
    }

    public void receiveDailyAward() {
        if(!isReceive) {
            buyMembershipService.receiveDailyAward();
        }
    }

    public void loadPageData() {
        buyMembershipService.loadPageData();
    }

    public void refreshRewardPrompt(int beanNumber, boolean isReceive) {
        this.isReceive = isReceive;
        set("rewardPrompt", "VIP每日领取" + beanNumber + "金豆");
        set("receiveBtnText", isReceive ? "今日已领" : "立即领取");
    }
    public void receiveReward() {
        isReceive = true;

        set("receiveBtnText", "今日已领");

        new TipsConfirmDialog(activity)
                .setDialogTitle("温馨提示")
                .setDialogContent("领取成功")
                .setDialogBtnText("我知道了")
                .show();

    }

    public void clearFreeComicList() {
        freeComicList.clear();
    }
    public void addFreeComicItem(int comicId,String coverImg ,String floatTips ,String title ,String[] tags) {
        freeComicList.add(new MembersFreeComicItemViewModel(comicId, coverImg, floatTips, title, tags));
    }
    public void refreshFreeComicAdapter() {
        freeComicAdapter.notifyDataSetChanged();
    }

    public void clearMembersPackageList() {
        membersPackageList.clear();
    }
    public void addMembersPackageItem(String describe, String buyPrice, String originalPrice, int beanReward, String cornerLabel) {
        membersPackageList.add(new MembersPackageItemViewModel(describe, buyPrice, originalPrice, beanReward, cornerLabel));
    }
    public void refreshMembersPackageAdapter() {
        membersPackageAdapter.notifyDataSetChanged();
    }

    public boolean haveChosen() {
        return ObjectUtil.nonNull(selectPackageItem);
    }
    public void setSelectPackageItem(MembersPackageItemViewModel selectPackageItem) {
        this.selectPackageItem = selectPackageItem;
        refreshBuyButtonUI();
    }
    public void setSelectPackageItem(int index) {
        if(ListUtil.notEmpty(membersPackageList)) {
            membersPackageList.get(index).toggle();
        }
    }

    //endregion

    //region #UI操作

    public void refreshUI() {
        refreshUserUI();
        refreshBuyButtonUI();
    }

    public void refreshUserUI() {
        boolean isLogin = UserEntity.self.isLogin();
        boolean isVIP = UserEntity.self.isVip();
        set("vipHeadWearVisible", isVIP ? View.VISIBLE : View.GONE);
        set("userHeadImage", UserEntity.self.getPortrait());
        set("userName", isLogin ? UserEntity.self.getName() : "大人！点这里登录");
        set("timeLimitPrompt", isVIP ? "将于" + UserEntity.self.getShortVipExpirationTime() + "过期" : "开通会员,享受多重特权!!");
    }

    public void refreshBuyButtonUI() {
        boolean haveChosen = ObjectUtil.nonNull(selectPackageItem);
        set("payButtonText",  UserEntity.self.isVip() ? "立即续费" : "立即支付");
        set("payButtonTextColor",  haveChosen ? "#624500" : "#909090");
        set("payButtonBg",  haveChosen ? R.drawable.app_buy_membership_button_yellow : R.drawable.app_buy_membership_button_gray);
    }

    public void showBuyResult() {
        if(ObjectUtil.nonNull(selectPackageItem)) {
            new BuyResultTipsDialog(activity, PayTipType.Membership)
                    .setMembershipDays(selectPackageItem.describe)
                    .show();
        }

    }

    public void showSpecialEvent(String imgUrl, String pageUrl) {
        new SpecialEventDialog(activity)
                .setImagePath(imgUrl)
                .setEventInfo(pageUrl, "").show();
    }

    //endregion #UI操作

    //region    #UI绑定 begin

    public MutableLiveData<Integer> getVipHeadWearVisible() {
        return get("vipHeadWearVisible");
    }

    public MutableLiveData<String> getUserHeadImage() {
        return get("userHeadImage");
    }
    public MutableLiveData<CharSequence> getUserName() {
        return get("userName");
    }
    public MutableLiveData<CharSequence> getTimeLimitPrompt() {
        return get("timeLimitPrompt");
    }

    public MutableLiveData<CharSequence> getRewardPrompt() {
        return get("rewardPrompt");
    }

    public MutableLiveData<CharSequence> getReceiveBtnText() {
        return get("receiveBtnText");
    }

    public MutableLiveData<CharSequence> getPayButtonText() {
        return get("payButtonText");
    }

    public MutableLiveData<String> getPayButtonTextColor() {
        return get("payButtonTextColor");
    }


    public MutableLiveData<Integer> getPayButtonBg() {
        return get("payButtonBg");
    }

    public BaseAdapter getMembersPackageAdapter() {
        return membersPackageAdapter;
    }

    public Adapter getFreeComicAdapter() {
        return freeComicAdapter;
    }

    public LayoutManager getFreeComicLayoutManager() {
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return manager;
    }

    public ItemDecoration[] getFreeComicItemDecorations() {
        return freeComicItemDecorations;
    }

    public BaseAdapter getVipPrivilegeAdapter() {
        return vipPrivilegeAdapter;
    }

    //endregion #UI绑定 end

    @AdapterEntityBind(viewRid = R.layout.layout_buy_membership_package_item)
    public class MembersPackageItemViewModel extends BaseObservable implements AutoVariable<LayoutBuyMembershipPackageItemBinding> {

        public final String describe;
        public final String buyPrice;
        public final String originalPrice;
        public final int    beanReward;
        public final String cornerLabel;

        private boolean haveChosen = false;

        public MembersPackageItemViewModel(String describe, String buyPrice, String originalPrice, int beanReward, String cornerLabel) {
            this.describe       = describe;
            this.buyPrice       = buyPrice;
            this.originalPrice  = originalPrice;
            this.beanReward     = beanReward;
            this.cornerLabel    = cornerLabel;
        }

        @Override
        public void bindVariable(LayoutBuyMembershipPackageItemBinding viewBind) {
            viewBind.setMembersPackageItemViewModel(this);
        }

        public void setHaveChosen(boolean haveChosen) {
            this.haveChosen = haveChosen;
            notifyPropertyChanged(BR.haveChosen);
        }

        public void toggle() {
            toggleSelectItem(this);
        }

        @Bindable
        public boolean getHaveChosen() {
            return haveChosen;
        }
        @Bindable
        public CharSequence getDescribe() {
            return describe;
        }
        @Bindable
        public CharSequence getBuyPrice() {
            return buyPrice;
        }
        @Bindable
        public CharSequence getOriginalPrice() {
            SpannableString  originalPriceBuilder = new SpannableString(originalPrice);
            originalPriceBuilder.setSpan(new StrikethroughSpan(), 3, originalPriceBuilder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            return originalPriceBuilder;
        }
        @Bindable
        public int getBeanRewardVisible() {
            return beanReward <= 0 ? View.GONE : View.VISIBLE;
        }
        @Bindable
        public CharSequence getBeanReward() {
            return "送" + beanReward + "金豆";
        }
        @Bindable
        public CharSequence getCornerLabel() {
            return cornerLabel;
        }

    }

    @AdapterEntityBind(viewRid = R.layout.layout_buy_membership_free_comic_item)
    public class MembersFreeComicItemViewModel extends BaseObservable implements AutoVariable<LayoutBuyMembershipFreeComicItemBinding> {

        public  final int       comicId;
        public  final String    title;

        private final String    coverImg;
        private final String    floatTips;
        private final String[]  tags;

        public MembersFreeComicItemViewModel(int comicId,String coverImg ,String floatTips ,String title ,String[] tags){
            this.comicId    = comicId;
            this.coverImg   = coverImg;
            this.floatTips  = floatTips;
            this.title      = title;
            this.tags       = tags;
        }

        @Override
        public void bindVariable(LayoutBuyMembershipFreeComicItemBinding viewBind) {
            viewBind.setMembersFreeComicItemViewModel(this);
        }

        @Bindable
        public String getCoverImg() {
            return coverImg;
        }

        @Bindable
        public CharSequence getFloatTips() {
            return floatTips;
        }

        @Bindable
        public CharSequence getTitle() {
            return title;
        }

        @Bindable
        public CharSequence getTags() {
            if(tags == null) return "";
            StringBuilder stringBuilder = new StringBuilder(tags.length);
            for (String str : tags){
                stringBuilder.append(str).append(" ");
            }
            return stringBuilder;
        }

    }

    @AdapterEntityBind(viewRid = R.layout.layout_buy_membership_vip_privilege_item)
    public class VipPrivilegeItemViewModel extends BaseObservable implements AutoVariable<LayoutBuyMembershipVipPrivilegeItemBinding> {

        public final VipPrivilegeType privilegeType;

        public VipPrivilegeItemViewModel(VipPrivilegeType privilegeType) {
            this.privilegeType = privilegeType;
        }

        @Override
        public void bindVariable(LayoutBuyMembershipVipPrivilegeItemBinding viewBind) {
            viewBind.setVipPrivilegeItemViewModel(this);
        }
    }

    public class GridSpacingItemDecoration extends ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }

            int parentWidth = parent.getWidth();
            view.getLayoutParams().width = (parentWidth / spanCount) - (outRect.left + outRect.right);
        }
    }

}
